package com.atech.ebayadmin.merchandise.action;
import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;
import org.springframework.dao.DataIntegrityViolationException;

import com.atech.ebayadmin.common.MdConstConfig;
import com.atech.ebayadmin.common.pager.Pager;
import com.atech.ebayadmin.common.pager.PagerHelper;
import com.atech.ebayadmin.common.struts.BaseAction;
import com.atech.ebayadmin.merchandise.model.ModifyHistory;
import com.atech.ebayadmin.merchandise.model.Record;
import com.atech.ebayadmin.merchandise.service.IBatchService;
import com.atech.ebayadmin.merchandise.service.IMerchandiseService;
import com.atech.ebayadmin.merchandise.vo.ModifyHistoryVO;
import com.atech.ebayadmin.merchandise.vo.RecordVO;
import com.atech.ebayadmin.system.service.ISystemService;
import com.atech.ebayadmin.system.util.JsonParser;
import com.atech.ebayadmin.system.vo.UserVO;

public class MerchandiseAction extends BaseAction{
	
    /**
	 * 
	 */
	private static final long serialVersionUID = 9121239445358723647L;
	private static final Log log = LogFactory.getLog(MerchandiseAction.class);
    private IMerchandiseService mdService;
    private IBatchService batchService;
    private ISystemService systemService;
	private Integer id;
	private Integer queryId;
	
	//Add for Create Record
	private Record reMd = new Record();
	private RecordVO reMdVO = new RecordVO();
	private Map prodType;
	private Map prodClass;
	//private Map equipClass;
	private Map fiberType;
	private Map currStatus;
	
	
	// Add for List Record
	private RecordVO reVO;
	private List<RecordVO> reList;
	private RecordVO dispRe = new RecordVO();
	private RecordVO srchCrt = new RecordVO();
	private RecordVO srchPreFill = new RecordVO();
	String[] selFilter;
	//Added by Doug
	String[] tmpSelFilter;
	
	private File importFile;
	
	// Add for modify history
	private List<ModifyHistoryVO> modHistyList;

	
	/**
	 * @return the message
	 */
	public String getMessage() {
		return message;
	}
	/**
	 * @param message the message to set
	 */
	public void setMessage(String message) {
		this.message = message;
	}
	
	protected String[] decodePaymentMethodList(String methods){
		String[] methodsArray = methods.split(",");
		return methodsArray;
	}
	
	// Add for create new record begin
	
	public String readDropDownDetails() throws Exception {
		this.setProdType(MdConstConfig.prodType);
		this.setProdClass(MdConstConfig.prodClass);
		//Revised by Doug on Oct19 to remove the drapdown of equipClass
		/*this.setEquipClass(MdConstConfig.equipClass);*/
		this.setFiberType(MdConstConfig.fiberType);
		this.setCurrStatus(MdConstConfig.currStatus);
        return SUCCESS;
    }
	
	public String createRecord(){
		try{
			UserVO user = (UserVO)super.getSession().get("User");//获取用户的会话对象
			//Commented by Doug since this is no longer needed in RscAdmin			
			//this.setAllEbayActByUserId(systemService.listEbayactByUser(user.getUserId()));
			this.readDropDownDetails();
			this.reMd.cleanData();
		}catch (Exception e) {
			e.printStackTrace();
		}
        return SUCCESS;
    }
			
		
	public String saveRecord(){
		log.info("进入商品保存接口");

		HttpServletRequest request = null;
		try{
			request = ServletActionContext.getRequest();
			UserVO user = (UserVO)super.getSession().get("User");//获取用户的会话对象
			reMdVO.setUserId(user.getUserId());
			reMd.setInputDate(new Date());
			String unitPrice = reMdVO.getUnitPrice();
			String fiberLength = reMdVO.getFiberLength();
			if (StringUtils.isNotBlank(unitPrice)) {
				reMd.setUnitPrice(new BigDecimal(unitPrice));
			}
			// Comment for change it to Integer from BigDecimal
			/*
			if (StringUtils.isNotBlank(fiberLength)) {
				reMd.setFiberLength(new BigDecimal(fiberLength));
			}*/
			System.err.println("=== Remarks ===" + reMdVO.getRemarks());
			System.err.println("=== UnitPirce ===" + reMdVO.getUnitPrice());
			Integer mdId = mdService.saveRecord(reMd);
			request.setAttribute("id","id");
			request.setAttribute("idValue", mdId);
			request.setAttribute("actionName", "viewRecord");
			request.setAttribute("message", "新资产添加成功!");
			
			//Added by Doug on Oct22. This one should be removed if we change the bean scope from session to prototype
			//To reproduce the issue:
			//Step1: create a new record with field A=x
			//Step2: modify an existing record, which has an empty value in field A
			//Step3: press save, x would be set as the value of field A
			reMd= new Record();
			
	        return SUCCESS;
		}catch (Exception e) {
			request.setAttribute("message", e.getMessage());
			return super.handleException(e);
		}
		
    }
	
	// Add for create new record end
	
	// Add for list record begin
	public String filterRecord(){
		
		//this.dispRe = null;
		//this.dispRe = new RecordVO();
		if (null == this.dispRe) {
			this.dispRe = new RecordVO();
		} 
		if (null != this.srchCrt) {
			srchPreFill = new RecordVO();
			
			//Added by Doug to do the prefill (for returning back case)
			HttpServletRequest request = ServletActionContext.getRequest();
			HttpSession session = request.getSession();
			if (null != session.getAttribute("srchCrt")) srchCrt = (RecordVO) session.getAttribute("srchCrt");
			selFilter = (String[]) session.getAttribute("selFilter");
			
			try {
				BeanUtils.copyProperties(srchPreFill, srchCrt);
			} catch (IllegalAccessException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		try{
			this.readDropDownDetails();
			HttpServletRequest request = super.getRequest();
			Pager pager = PagerHelper.getPager(request);
			request.setAttribute("pager", pager);
		}catch (Exception e) {
			e.printStackTrace();
		}
        return SUCCESS;
    }
	
	public String listRecord(){
		HttpServletRequest request = ServletActionContext.getRequest();
		Map filterList = new HashMap();
		/*this.selFilter = request.getParameterValues("selFilter");*/
		
		/*
		 * Doug: We needed to add tmpSelFilter to temporally store the checkbox status
		 * If we directly use: 
		 * 		this.selFilter = request.getParameterValues("selFilter");
		 * The value of this.selFilter would not be correct when using Pager 
		 * (listRecord would be called whenever we clicked 'Next' or 'Previous, however this.selFilter would be set to this.selFilter[0]=assetsNum)
		 * To make sure we're using the correct checkbox status (in pagination); we need to use clone
		 */
		//the filter list should be bigger than 4
		if (null != request.getParameterValues("selFilter") && request.getParameterValues("selFilter").length >= 4) {
			this.selFilter = request.getParameterValues("selFilter");
			this.tmpSelFilter=this.selFilter.clone();
		}else if (null != this.tmpSelFilter)
		{
			this.selFilter=this.tmpSelFilter.clone();			
		}else{
		/*
		 * Doug on Sep24, 2012
		 * The checking on null 'this.tmpSelFilter' is for following issue:
		 * - 系统初次启动，新增record，成功，按返回，exception found
		 * Coz the '返回' button in message.jsp directly calls action listRe & if that is the first time for listRe to be called (without calling filterRe beforehand)
		 * this.tmpSelFilter would be null. Therefore if this.tmpSelFilter is null, we give the user a 'No Record Found'
		 */
			this.setReList(null);
			return SUCCESS;
		}
		
		//Added by Doug on Sep16 to fix the “返回” issue in list_record
		/*
		 * We need to clear the content of dispRe every time. Otherwise when doing "return back" & "proceed", 
		 * if the number of checked box less the previous one, the new number won't take effect
		 */
		this.dispRe.clear();
		
		if (null != selFilter) {
			for (int i = 0; i < selFilter.length; i++) {
				System.err.println("===== filter item [" + i + "]:" + selFilter[i]);
				String key = selFilter[i];
				
				//If a checkbox is checked, key here should not be NULL (for example, would be 'value="assetsNum"') 
				if (StringUtils.isNotBlank(key)) {
					try {
						//User input values stored in srchCrt
						String value = BeanUtils.getProperty(srchCrt, key);
						System.err.println("========== get bean field [" + key + "]" + "====" + value);
						filterList.put(key, value);
						BeanUtils.setProperty(dispRe, key, "1");
					} catch (IllegalAccessException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (InvocationTargetException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (NoSuchMethodException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				
			}
			System.err.println("==========selfnum in the bean========" + dispRe.getSelfNum());
		}
		
		//Added by Doug on Sep18 for prefilling when 'returning back'
		HttpSession session = request.getSession();
		session.setAttribute("srchCrt", srchCrt);
		session.setAttribute("selFilter", selFilter);
		
		try{
			this.readDropDownDetails();
			RecordVO vo = new RecordVO();
			log.info("进入商品查询接口");
			Pager pager = PagerHelper.getPager(request);
			List<RecordVO> volist = mdService.listRecord(filterList, pager);
			this.setReList(volist);
			System.err.println("==========volist========" + volist);
		//	System.err.println("volist Json Data: \n" + JsonParser.parseRecordsToJson(volist));
			request.setAttribute("pager", pager);
		}catch (Exception e) {
			e.printStackTrace();
		}
        return SUCCESS;
    }
	// Add for list record end
	
	// Add for modify record begin
	public String modifyRecord(){
		try{
			System.err.println("=== modify record ===" + this.id);
			
			reMd = mdService.getRecord(this.id);
			reVO = mdService.poToVo(reMd);
			this.readDropDownDetails();

			System.err.println("=== reVO ===" +reVO);
			//setMd(mdService.getMerchandise(getId()));
	        return SUCCESS;
		}catch (Exception e) {
			ServletActionContext.getRequest().setAttribute("message", e.getMessage());
			return super.handleException(e);
		}
    }
	
	public String updateRecord() throws Exception {	
		log.info("进入商品更新接口");
		try{
			HttpServletRequest request = ServletActionContext.getRequest();
			System.err.println("====== modify SequenceNum ====" + reMd.getSequenceNum());
			mdService.updateRecord(reMd);
			UserVO user = (UserVO)super.getSession().get("User");//获取用户的会话对象
			mdService.saveModHisty(user, reMd);
			request.setAttribute("id","id");
			request.setAttribute("idValue", reMd.getSequenceNum());
			request.setAttribute("actionName", "listRe");
			ServletActionContext.getRequest().setAttribute("message", "资产修改成功!");
			
			return SUCCESS;
		}catch (Exception e) {
			ServletActionContext.getRequest().setAttribute("message", e.getMessage());
			return super.handleException(e);
		}
    }
	// Add for modify record end
	
	// Add for save modify record history end
	
	// Add for get modify history begin
	public String rtrvModifyHisty() {
		List<ModifyHistoryVO> volist;
		try {
			volist = mdService.rtrvModifyHisty(this.id);
			this.modHistyList = volist;
		} catch (Exception e) {
			e.printStackTrace();
			return ERROR;
		}
		
		return SUCCESS;
	}
	
	// Add for get modify history end
	
	// Add for delete select record begin
	public String delSelectRe(){
		HttpServletRequest request = ServletActionContext.getRequest();
		String[] selDelRe = request.getParameterValues("delList");
		Map result = new HashMap();
		try{
			mdService.deleteSlctRe(selDelRe, result);
			this.setMessage("the Item(s) you selected is/are deleted,please click close button to close the window");
		}catch (Exception e) {
			e.printStackTrace();
			this.setMessage("the Item deleted failure: "+e.getMessage());
			
		}
		int ss = 0;
		List ssl = (List)result.get("S");
		if (null != ssl) {
			ss = ssl.size();
		}
		
		//"if-else" Added by Doug on 2013-01-30
		//Otherwise, if user doesn't select any entries & click "delete", null-pointer exception would be thrown
		if (null != selDelRe){
			ServletActionContext.getRequest().setAttribute("message", "选择删除资产总共" 
				+ selDelRe.length + "条纪录." + "成功删除资产" + ss + "条纪录");
		}else{
			ServletActionContext.getRequest().setAttribute("message", "请先选择需要删除的条目");
		}
		
		return SUCCESS;
	}
	// Add for delete select record end


	//show import file jsp
	public String batchService() throws Exception {
		
		try{
			HttpServletRequest request = ServletActionContext.getRequest();
			
			log.info("batchService");
			
	        return SUCCESS;
		}catch (Exception e) {
			ServletActionContext.getRequest().setAttribute("message", e.getMessage());
			return super.handleException(e);
		}
    }
	
	//show import file jsp
	public String importFile() throws Exception {
		
		try{
			HttpServletRequest request = ServletActionContext.getRequest();
			UserVO user = (UserVO)super.getSession().get("User");//获取用户的会话对象
			reMd.setUserId(user.getUserId());
			reMd.setInputDate(new Date());
			
			batchService.importFile(user, reMd.getImportFilePath());
			
		}catch (Exception e) {
			ServletActionContext.getRequest().setAttribute("message", "批量载入数据遇到错误！请重试！" + e.getMessage());
			return super.handleException(e);
		}
		ServletActionContext.getRequest().setAttribute("message", "批量载入数据成功！请转入资产记录查询界面查询详细信息。共增加资产"+ batchService.getNumOfNew()+"条，修改资产"+batchService.getNumOfUpdated()+"条。");
        return SUCCESS;
    }
	
	public String exportFile() throws Exception {
		
		try{
			log.info("[MerchandiseAction].exportFile in ");
			HttpServletRequest request = ServletActionContext.getRequest();
			Map filterList = new HashMap();
			if (null != selFilter) {
				for (int i = 0; i < selFilter.length; i++) {
					System.err.println("===== filter item [" + i + "]:" + selFilter[i]);
					String key = selFilter[i];
					if (StringUtils.isNotBlank(key)) {
						try {
							String value = BeanUtils.getProperty(srchCrt, key);
							System.err.println("========== get bean field [" + key + "]" + "====" + value);
							filterList.put(key, value);
						} catch (IllegalAccessException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (InvocationTargetException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (NoSuchMethodException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
					
				}
				System.err.println("==========selfnum in the bean========" + dispRe.getSelfNum());
			}

			batchService.exportFile(filterList, dispRe);
			
		}catch (Exception e) {
			e.printStackTrace();
			
			String msg = "批量输出数据遇到错误！请重试！";
			
			if(StringUtils.isNotBlank(e.getMessage())){
				msg = msg + e.getMessage();
			}
			
			ServletActionContext.getRequest().setAttribute("message",msg);
			return ERROR;
		}
		
        return null;
	}
	
	/**
	 * @return the serialVersionUID
	 */
	public static long getSerialVersionUID() {
		return serialVersionUID;
	}

	/**
	 * @return the id
	 */
	public Integer getId() {
		return id;
	}

	/**
	 * @param id the id to set
	 */
	public void setId(Integer id) {
		this.id = id;
	}

	/**
	 * @return the mdService
	 */
	public IMerchandiseService getMdService() {
		return mdService;
	}
	/**
	 * @param mdService the mdService to set
	 */
	public void setMdService(IMerchandiseService mdService) {
		this.mdService = mdService;
	}
	/**
	 * @return the systemService
	 */
	public ISystemService getSystemService() {
		return systemService;
	}
	/**
	 * @param systemService the systemService to set
	 */
	public void setSystemService(ISystemService systemService) {
		this.systemService = systemService;
	}
	public Integer getQueryId() {
		return queryId;
	}
	public void setQueryId(Integer queryId) {
		this.queryId = queryId;
	}
	/**
	 * @return the prodType
	 */
	public Map getProdType() {
		return prodType;
	}
	/**
	 * @param prodType the prodType to set
	 */
	public void setProdType(Map prodType) {
		this.prodType = prodType;
	}
	/**
	 * @return the prodClass
	 */
	public Map getProdClass() {
		return prodClass;
	}
	/**
	 * @param prodClass the prodClass to set
	 */
	public void setProdClass(Map prodClass) {
		this.prodClass = prodClass;
	}
	/**
	 * @return the equipClass
	 */
	/*public Map getEquipClass() {
		return equipClass;
	}*/
	/**
	 * @param equipClass the equipClass to set
	 */
	/*public void setEquipClass(Map equipClass) {
		this.equipClass = equipClass;
	}*/
	/**
	 * @return the fiberType
	 */
	public Map getFiberType() {
		return fiberType;
	}
	/**
	 * @param fiberType the fiberType to set
	 */
	public void setFiberType(Map fiberType) {
		this.fiberType = fiberType;
	}
	/**
	 * @return the currStatus
	 */
	public Map getCurrStatus() {
		return currStatus;
	}
	/**
	 * @param currStatus the currStatus to set
	 */
	public void setCurrStatus(Map currStatus) {
		this.currStatus = currStatus;
	}
	/**
	 * @return the reMd
	 */
	public Record getReMd() {
		return reMd;
	}
	/**
	 * @param reMd the reMd to set
	 */
	public void setReMd(Record reMd) {
		this.reMd = reMd;
	}
	/**
	 * @return the reList
	 */
	public List<RecordVO> getReList() {
		return reList;
	}
	/**
	 * @param reList the reList to set
	 */
	public void setReList(List<RecordVO> reList) {
		this.reList = reList;
	}
	/**
	 * @return the reVO
	 */
	public RecordVO getReVO() {
		return reVO;
	}
	/**
	 * @param reVO the reVO to set
	 */
	public void setReVO(RecordVO reVO) {
		this.reVO = reVO;
	}
	/**
	 * @return the dispRe
	 */
	public RecordVO getDispRe() {
		return dispRe;
	}
	/**
	 * @param dispRe the dispRe to set
	 */
	public void setDispRe(RecordVO dispRe) {
		this.dispRe = dispRe;
	}
	public File getImportFile() {
		return importFile;
	}

	public void setImportFile(File importFile) {
		this.importFile = importFile;
	}
	public IBatchService getBatchService() {
		return batchService;
	}
	public void setBatchService(IBatchService batchService) {
		this.batchService = batchService;
	}
	/**
	 * @return the srchCrt
	 */
	public RecordVO getSrchCrt() {
		return srchCrt;
	}
	/**
	 * @param srchCrt the srchCrt to set
	 */
	public void setSrchCrt(RecordVO srchCrt) {
		this.srchCrt = srchCrt;
	}
	/**
	 * @return the srchPreFill
	 */
	public RecordVO getSrchPreFill() {
		return srchPreFill;
	}
	/**
	 * @param srchPreFill the srchPreFill to set
	 */
	public void setSrchPreFill(RecordVO srchPreFill) {
		this.srchPreFill = srchPreFill;
	}
	/**
	 * @return the selFilter
	 */
	public String[] getSelFilter() {
		return selFilter;
	}
	/**
	 * @param selFilter the selFilter to set
	 */
	public void setSelFilter(String[] selFilter) {
		this.selFilter = selFilter;
	}
	/**
	 * @return the reMdVO
	 */
	public RecordVO getReMdVO() {
		return reMdVO;
	}
	/**
	 * @param reMdVO the reMdVO to set
	 */
	public void setReMdVO(RecordVO reMdVO) {
		this.reMdVO = reMdVO;
	}
	/**
	 * @return the modHisyList
	 */
	public List<ModifyHistoryVO> getModHistyList() {
		return modHistyList;
	}
	/**
	 * @param modHisyList the modHisyList to set
	 */
	public void setModHistyList(List<ModifyHistoryVO> modHistyList) {
		this.modHistyList = modHistyList;
	}
			
}
